<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\api\controller;

use app\api\model\Setting as SettingModel;
use app\api\model\UploadFile as UploadFileModel;
use app\api\service\User as UserService;
use app\common\enum\Setting as SettingEnum;
use app\common\enum\file\FileType as FileTypeEnum;
use app\common\library\storage\Driver as StorageDriver;
use cores\exception\BaseException;
use OSS\Core\OssException;
use OSS\OssClient;

/**
 * 文件库管理
 * Class Upload
 * @package app\api\controller
 */
class Upload extends Controller
{
    // 当前商城的上传设置
    private $config;

    /**
     * 构造方法
     * @throws BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function initialize()
    {
        parent::initialize();
        // 验证登录
        UserService::isLogin(true);
        // 存储配置信息
        $this->config = SettingModel::getItem(SettingEnum::STORAGE);
    }

    /**
     * 图片上传接口
     * @return array|\think\response\Json
     * @throws BaseException
     * @throws \think\Exception
     */
    public function image()
    {
        // 当前用户ID
        $userId = UserService::getCurrentLoginUserId();
        // 实例化存储驱动
        $storage = new StorageDriver($this->config);
        // 设置上传文件的信息
        $storage->setUploadFile('file')
            ->setRootDirName((string)$this->storeId)
            ->setValidationScene('image');
        // 执行文件上传
        if (!$storage->upload()) {
            return $this->renderError('图片上传失败：' . $storage->getError());
        }
        // 文件信息
        $fileInfo = $storage->getSaveFileInfo();
        $fileInfo = $this->ossDeal($fileInfo);
        // 添加文件库记录
        $model = new UploadFileModel;
        $model->add($fileInfo, FileTypeEnum::IMAGE, $userId);
        // 图片上传成功
        return $this->renderSuccess(['fileInfo' => $model->toArray()], '图片上传成功');
    }


    
    //图片上传oss存储
    public function ossDeal($datas):Array {
        $originName = $datas['file_name'];//源文件  
        $tmpFile  = $_SERVER['DOCUMENT_ROOT'].'/uploads\/'.$datas['file_path'];  //临时文件地址

        $ossPath = 'geekShoppingMall/'.date('Y-m-d').'/'.date('Hi') .mt_rand(10000,99999);
        $object = $ossPath .'.' .$this->getExtension($originName);

        //获取OSS参数值
        $oss = config('app.oss');
        $KeyId     = $oss['accessKeyId'];
        $KeySecret = $oss['sccessKeySecret'];
        $EndPoint  = $oss['endpoint'];
        $Bucket    = $oss['bucket'];
        // $object    = date("Ymd") . "/";

        $ossClient = new OssClient($KeyId, $KeySecret, $EndPoint);

        // 执行上传并获取返回 oss 信息
        $info = $ossClient->uploadFile($Bucket, $object, $tmpFile);
        $ossUrl = $info['oss-request-url'];
        // 如果图片的协议是http，则转换成https
        if (substr($ossUrl, 0, 4) == 'http') {
            $ossUrl = substr_replace($ossUrl, 'https', 0, 4);
        }
        //上传成功后清除临时文件夹和文件
        if (file_exists($tmpFile)) {
            unlink($tmpFile);
        }  
         //删除空文件夹
         if (file_exists($_SERVER['DOCUMENT_ROOT'].'/uploads/10001/'.date("Ymd",time()))){
            rmdir($_SERVER['DOCUMENT_ROOT'].'/uploads/10001/'.date("Ymd",time()));
        }

        // if (file_exists($tmpFile)) unlink($tmpFile);
        // $datas['url'] = $ossUrl ;
        $new_url= parse_url($ossUrl);
        $new_url= substr($new_url['path'],1);
        $datas['file_url'] = $this->getOssImg($new_url,630720000);
        $datas['file_path'] =  $ossUrl;  
        $datas['oss_expires_time'] =  time()+630720000;  //oss过期时间
        // $datas['file_name'] =  basename($ossUrl);

        RETURN $datas;
    }

     
    //返回前端显示图片
    public function getOssImg($path, $timeout) {
        try {
            //获取OSS参数值
            $oss = config('app.oss');
            $KeyId         = $oss['accessKeyId'];
            $KeySecret     = $oss['sccessKeySecret'];
            // $securityToken = $oss['securityToken'];
            // $EndPoint      = $oss['endpoint'];
            // $EndPoint      = 'https://oss-cn-hangzhou.aliyuncs.com';
            $EndPoint  = $oss['endpoint'];
            $Bucket        = $oss['bucket'];
            // $object        = date("Ymd") . "/" . $path;
            $object        =$path ;
            // $timeout       = 32400;
            $ossClient = new OssClient($KeyId, $KeySecret, $EndPoint, false);
            $signedUrl = $ossClient->signUrl($Bucket, $object, $timeout);

            return $signedUrl;
        } catch (OssException $e) {
            $rearr['msg'] = '方法错误';
            return $rearr;
        }
    }

    
    /**
     * 返回文件扩展名
     *
     * @param $fileName
     * @return mixed
     */
    private function getExtension($fileName){
        return pathinfo($fileName)['extension'];
    }


}
